import ctypes
import time
import win32api
import win32con
import win32gui
import ctypes.wintypes


def get_window_rect(hwnd):  # 大佬优化的窗口识别程序，但是我没有用，因为懒
    try:
        f = ctypes.windll.dwmapi.DwmGetWindowAttribute
    except WindowsError:
        f = None
    if f:
        rect = ctypes.wintypes.RECT()
        DWMWA_EXTENDED_FRAME_BOUNDS = 9
        f(ctypes.wintypes.HWND(hwnd),
          ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
          ctypes.byref(rect),
          ctypes.sizeof(rect)
          )
        return rect.left, rect.top, rect.right, rect.bottom


hwnd = win32gui.FindWindow(None, "动物餐厅")  # 父句柄
hwndChildList = []
win32gui.EnumChildWindows(hwnd, lambda hwnd, param: param.append(hwnd), hwndChildList)
hwnd1 = win32gui.FindWindowEx(hwndChildList[0], 0, None, None)
win32gui.SetForegroundWindow(hwnd)  # 指定句柄设置为前台，也就是激活
win32gui.ShowWindow(hwnd, win32con.SW_NORMAL)  # 显示最前 从最小化模式显示为正常
# windowRec = get_window_rect(hwnd)  # 目标子句柄窗口的坐标 左上右下边到屏幕边的距离
windowRec = win32gui.GetWindowRect(hwnd1)
left, top = windowRec[0], windowRec[1]
print(windowRec)
width, height = windowRec[2] - windowRec[0], windowRec[3] - windowRec[1]


def locate_relativity():
    while 1:
        tempt = win32api.GetCursorPos()  # 记录鼠标所处位置的坐标
        print(tempt)
        x = tempt[0] - windowRec[0]  # 计算相对x坐标
        y = tempt[1] - windowRec[1]  # 计算相对y坐标
        print(str(x) + ",", y)
        time.sleep(0.5)  # 每0.5s输出一次


locate_relativity()